import { updBuy } from '@/services/user';
import { colorStr, getQueryParams, selectOne } from '@/utils/utils';
import { DownOutlined, HomeOutlined } from '@ant-design/icons';
import { Breadcrumb, Button, Dropdown, Input, Menu, message, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import { CirclePicker } from 'react-color';
import { history } from 'umi';
import QRcode from './components/QRcode';
import styles from './index.less';

interface Props {
  lastRoute: any;
  now: string;
  setColorParent: any;
}

const TopBread: React.FC<Props> = ({ lastRoute, now, setColorParent }) => {
  const qs = getQueryParams();
  let isNotLogin = !localStorage.getItem('qs');

  // 充值弹窗的visible
  const [moneyModal, setMoneyModal] = useState<boolean>(false);
  // 查看余额弹窗的visible
  const [seeMoney, setSeeMoney] = useState<boolean>(false);
  // 修改主题颜色弹窗的visible
  const [colorModal, setColorModal] = useState<boolean>(false);
  // 充值二维码
  const [qrCode, setQrCode] = useState<boolean>(false);
  // 主题颜色的值
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const [colorCurrent, setColorCurrent] = useState<string>('');
  const [money, setMoney] = useState<string>('');
  const [otherMoney, setOtherMoney] = useState<string>('');
  const [selected, setSelected] = useState<string>('');
  const SELECT_ONE = [
    { key: 'thirty', value: 30 },
    { key: 'fifty', value: 50 },
    { key: 'hundred', value: 100 },
    { key: 'fiveHundreds', value: 500 },
    { key: 'thousand', value: 1000 },
  ];

  useEffect(() => {
    if (localStorage.getItem('qs')) {
      selectOne(qs.role);
    }
  }, [qs.role]);

  // 自定义捐款金额的校验
  const moneyInputChange = (e: any) => {
    const { value: inputValue } = e.target;
    const reg = /^\+?[1-9]\d*$/;
    if (reg.test(inputValue) || inputValue === '') {
      if (inputValue > 10000) {
        setOtherMoney('10000');
      } else {
        setOtherMoney(inputValue);
      }
    }
  };

  // 修改主题颜色
  const colorChange = () => {
    setColorModal(false);
    setColor(colorCurrent);
    setColorParent(colorCurrent);
    localStorage.setItem('color', colorCurrent);
  };

  const rechargeMoney = async () => {
    try {
      await updBuy({
        id: qs.id,
        isMoney: '1',
        money: otherMoney !== '' ? qs.money + Number(otherMoney) : qs.money + Number(money),
      }).then(() => {
        message.loading({ content: '正在虚拟支付中......' });
        setTimeout(() => {
          setMoney('');
          selectOne('1');
          setQrCode(false);
          message.success('充值成功！');
        }, 3000);
      });
    } catch (error) {
      console.log(error);
    }
  };

  const handleCancel = () => {
    setMoney('');
    setSelected('');
    setMoneyModal(false);
  };
  const showMoney = () => {
    setSeeMoney(true);
  };

  const showModal = () => {
    setMoneyModal(true);
    setSeeMoney(false);
  };

  const menu = (
    <Menu>
      {qs.role === '3' ? (
        <Menu.Item key={'1'}>
          <div
            onClick={() => {
              history.push({
                pathname: '/back',
              });
            }}
          >
            进入后台
          </div>
        </Menu.Item>
      ) : (
        <Menu.Item key={'1'}>
          <div
            onClick={() => {
              history.push({
                pathname: '/changeInformation',
                query: { lastRoute: lastRoute, userRole: 'changeUser' },
              });
            }}
          >
            修改信息
          </div>
        </Menu.Item>
      )}
      <Menu.Item key={'2'}>
        <div onClick={showMoney}>查看余额</div>
      </Menu.Item>
      <Menu.Item key={'3'}>
        <div
          onClick={() => {
            setColorModal(true);
          }}
        >
          修改主题颜色
        </div>
      </Menu.Item>
      <Menu.Item key={'4'}>
        <div
          onClick={() => {
            history.push('/');
            localStorage.removeItem('qs');
            localStorage.removeItem('color');
            if (now === '商城首页') {
              window.location.reload();
            }
          }}
        >
          退出登录
        </div>
      </Menu.Item>
    </Menu>
  );
  return (
    <div className={styles.headerContainer} style={{ height: now === '店铺首页' ? 72 : 51 }}>
      {isNotLogin ? (
        <div className={styles.notlogin}>
          你好，
          <span
            className={styles.notloginText}
            onClick={() => {
              history.push('/login&register');
            }}
          >
            请<span style={{ cursor: 'pointer', color: `${color}` }}>登录</span>
          </span>
          ！
          <span
            className={styles.notloginText}
            style={{ cursor: 'pointer', color: `${color}` }}
            onClick={() => {
              history.push({
                pathname: '/login&register',
                query: { register: 'true' },
              });
            }}
          >
            免费注册
          </span>
        </div>
      ) : (
        <div
          className={styles.header}
          style={{ color: `${color}`, height: now === '店铺首页' ? 80 : 52 }}
        >
          {now === '商城首页' ? (
            <div className={styles.homeHead}>欢迎来到四季养生购物网站！</div>
          ) : (
            <Breadcrumb className={styles.breadcrumb} style={{ color: `${color}` }}>
              <Breadcrumb.Item onClick={history.goBack}>
                <HomeOutlined style={{ fontSize: 16, marginRight: 4 }} />
                <span>{lastRoute}</span>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                <span style={{ color: `${color}` }}>{now}</span>
              </Breadcrumb.Item>
            </Breadcrumb>
          )}
          <div className={styles.headRight}>
            <Dropdown overlay={menu}>
              <span className={styles.dropDown} onClick={(e) => e.preventDefault()}>
                个人中心
                <DownOutlined style={{ fontSize: 16, marginLeft: 5, marginTop: 2 }} />
              </span>
            </Dropdown>
          </div>
          <Modal
            title="账户充值"
            visible={moneyModal}
            width={788}
            className={styles.moneyModal}
            onCancel={handleCancel}
            footer={[
              <div key="count" className={styles.count}>
                合计：
                {!(money === '' && otherMoney === '') && (
                  <>
                    <span className={styles.agoCount}>
                      {otherMoney != '' ? otherMoney : money}元
                    </span>
                    {otherMoney != ''
                      ? (JSON.parse(otherMoney) * 0.9).toFixed(0)
                      : money != ''
                      ? JSON.parse(money) * 0.9
                      : ''}
                    元
                  </>
                )}
              </div>,
              <Button
                key="submit"
                type="primary"
                onClick={() => {
                  if (money !== '' || otherMoney !== '') {
                    setMoneyModal(false);
                    setQrCode(true);
                  } else {
                    message.error('请选择要充值的金额！');
                  }
                }}
                style={{ backgroundColor: colorStr(5) }}
              >
                充值
              </Button>,
              <Button key="back" onClick={handleCancel}>
                取消
              </Button>,
            ]}
          >
            <div className={styles.moneyModalDiv}>
              {`充值账号：`}
              <span style={{ color: colorStr(9) }}>{`"${JSON.stringify(qs.tel)?.substring(
                1,
                4,
              )}****${JSON.stringify(qs.tel)?.substr(-5)}`}</span>
              {`（${qs.nickname}）`}
            </div>
            <div className={styles.moneyItems}>
              {SELECT_ONE.map((item: any) => (
                <div
                  key={item.key}
                  onClick={() => {
                    setSelected(item.key);
                    setMoney(item.value);
                    setOtherMoney('');
                  }}
                  className={selected === item.key ? styles.selectedMoney : styles.selectMoney}
                  style={{
                    border: selected === item.key ? `1px solid ${colorStr(6)}` : '',
                  }}
                >
                  {item.value}元
                </div>
              ))}
            </div>
            <div className={styles.moneyItems}>
              <div
                key={'others'}
                onClick={() => {
                  setMoney('');
                  setSelected('others');
                }}
                className={selected === 'others' ? styles.selectedMoney : styles.selectMoney}
                style={{
                  border: selected === 'others' ? `1px solid ${colorStr(6)}` : '',
                }}
              >
                <Input
                  value={otherMoney}
                  className={styles.inputMoney}
                  placeholder={'其他数量'}
                  onChange={moneyInputChange}
                  maxLength={5}
                  bordered={false}
                  suffix={selected === 'others' ? '元' : null}
                />
              </div>
            </div>
          </Modal>
          <Modal
            title="查看余额"
            visible={seeMoney}
            centered={true}
            onCancel={() => {
              setSeeMoney(false);
            }}
            footer={
              <div>
                <Button onClick={showModal}>前去充值</Button>
                <Button
                  onClick={() => {
                    setSeeMoney(false);
                  }}
                >
                  我知道了
                </Button>
              </div>
            }
          >
            <div className={styles.seeModal}>
              <span style={{ fontSize: 15 }}>您的余额为：¥{qs.money.toFixed(2)}</span>
            </div>
          </Modal>
          <Modal
            title="修改主题颜色"
            visible={colorModal}
            onCancel={() => {
              setColorModal(false);
            }}
            footer={
              <div>
                <Button onClick={colorChange}>提交</Button>
                <Button
                  onClick={() => {
                    setColorModal(false);
                  }}
                >
                  取消
                </Button>
              </div>
            }
          >
            <div className={styles.colorPicker}>
              <CirclePicker
                onChangeComplete={({ hex }) => {
                  setColorCurrent(hex);
                }}
              />
              <div className={styles.colorBox}>
                <span>颜色预览：</span>
                <div
                  className={styles.colorDiv}
                  style={{ background: `${colorCurrent === '' ? color : colorCurrent}` }}
                />
              </div>
            </div>
          </Modal>
          <QRcode
            visible={qrCode}
            onCancel={() => {
              setQrCode(false);
            }}
            moneyCount={otherMoney === '' ? money : otherMoney}
            rechargeMoney={rechargeMoney}
          />
        </div>
      )}
    </div>
  );
};

export default TopBread;
